var gulp = require('gulp');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var autoprefixer = require('gulp-autoprefixer');
var uglify = require('gulp-uglify');
var zip = require('gulp-zip');

const del = require('del'),
	rev = require('gulp-rev'),
	handlebars = require('gulp-compile-handlebars'),
	rename = require('gulp-rename'),
	fs = require('fs');

var cheerhelper = require('./scripts/cheerhelper').CheerHelper;

var devHandlebarOpts = {
	helpers: {
		jsPath: function (path, context) {
			// var fullPath = context.data.root[path + '.js'];
			// return fullPath.substr(0, fullPath.length - 3);
			return path;
		}
	}
};

var productionHandlebarOpts = {
	helpers: {
		jsPath: function (path, context) {
			 // console.log('PATH-----' + path);
			var fullPath = context.data.root[path + '.js'];
			 // console.log('FULLPATH-----' + fullPath);
			return fullPath.substr(0, fullPath.length - 3);
		}
	}
};

gulp.task('sass', function () {
	gulp.src(['./dev/scss/*.scss'])
		.pipe(sourcemaps.init())
		.pipe(sass())
		.pipe(autoprefixer())
		.pipe(sourcemaps.write())
		.pipe(gulp.dest('./dev/css'));
	cheerhelper.log('sass compile success');
});


gulp.task('sass:watch', function () {
	gulp.watch('./dev/scss/*.scss', ['sass']);
});

// backup
gulp.task('backup', function () {
	return gulp.src('./release/**')
		.pipe(zip(new Date().format('yyyyMMdd_hhmmss') + '.zip'))
		.pipe(gulp.dest('./backup'));
});

// clean
gulp.task('clean', ['backup'], function () {
	cheerhelper.log('Starting clean...');
	return del(['./release/**', './temp/**']).then(function (paths) {
		cheerhelper.log('All files cleaned!');
	});
});

// 新建发布目录
gulp.task('move', ['clean'], function () {
	return gulp.src(['./dev/**', '!./dev/scss', '!./dev/scss/**', './dev/template', '!./dev/template/**', '!./dev/js', '!./dev/js/**']).pipe(gulp.dest('./release'));
});

// 编译sass&压缩css
gulp.task('sass-compress', ['move'], function () {
	return gulp.src('./dev/scss/*.scss')
		.pipe(sass({
			outputStyle: 'compressed'
		}))
		.pipe(autoprefixer())

		.pipe(gulp.dest('./release/css'));
});

// 1.给所有js/**/*.js添加hash
gulp.task('rev_js', ['sass-compress'], function () {
	return gulp.src(['./dev/js/**/*js', '!./dev/js/common/require_config.js'])
		.pipe(rev())
		.pipe(gulp.dest('./release/js'))
		.pipe(rev.manifest())
		.pipe(gulp.dest('.'));
});

// 2.编译require_config.js模板为包含实际路径配置的js文件，并给require_config.js添加hash - 生产环境
gulp.task('compile_rev_require_js', ['rev_js'], function () {
	var manifest = JSON.parse(fs.readFileSync('./rev-manifest.json', 'utf8'));
	return gulp.src('./dev/template/require_config.hbs')
		.pipe(handlebars(manifest, productionHandlebarOpts))
		.pipe(rename('require_config.js'))
		.pipe(rev())
		.pipe(gulp.dest('./release/js/common'))
		.pipe(rev.manifest({
			merge: true
		}))
		.pipe(gulp.dest('.'));
});

// 3.编译启动页面，替换页面里的require_config.js为实际路径（with hash）
gulp.task('compile_launchers_page', ['compile_rev_require_js'], function () {
	var manifest = JSON.parse(fs.readFileSync('./rev-manifest.json', 'utf8'));
	return gulp.src('./dev/template/pages/**/*.hbs')
		.pipe(handlebars(manifest, productionHandlebarOpts))
		.pipe(rename(function (path) {
			path.extname = '.html';
		}))
		.pipe(gulp.dest('./release'));
});

// uglifyJs
gulp.task('uglifyJs', ['compile_launchers_page'], function () {
	return gulp.src(['./release/js/**/*js'])
		// uglifyJs
		// .pipe(uglify({
		// 	mangle: false,
		// 	compress: {
		// 		drop_console: true
		// 	}
		// }))
		.pipe(gulp.dest('./release/js'));
});

// override
gulp.task('override', ['uglifyJs'], function () {
	return gulp.src('./override/**').pipe(gulp.dest('./release'));
});

// 编译require_config.js模板为包含实际路径配置的js文件 - 开发环境
gulp.task('compile_require_config_dev', function () {
	gulp.src('./dev/template/require_config.hbs')
		.pipe(handlebars({}, devHandlebarOpts))
		.pipe(rename('require_config.js'))
		.pipe(gulp.dest('./dev/js/common'));
	
	gulp.src('./dev/template/pages/**/*.hbs')
		.pipe(handlebars({}, devHandlebarOpts))
		.pipe(rename(function (path) {
			path.extname = '.html';
		}))
		.pipe(gulp.dest('./dev'));
});

//**********************EXECUTABLE************************
gulp.task('dev', ['sass', 'sass:watch'], function () {
	gulp.watch('./dev/template/**/*.hbs', ['compile_require_config_dev']);
});

gulp.task('release', ['override'], function () {
	gulp.src('./release/**')
		.pipe(zip('release.zip'))
		.pipe(gulp.dest('./release'));
});

gulp.task('bower', function () {
	gulp.src('./bower_components/**').pipe(gulp.dest('./dev/lib'));
});